package com.lgc.javathread.locktest.synchronizdAndLock.synchronizedTest;

import java.util.concurrent.TimeUnit;

public class Test1 {
    public static void main(String[] args) {
        Test1 test1 = new Test1();
        /*for (int i = 0; i < 5; i++) {
            new Thread(test1::m1).start();
        }*/
        //m1和m2互斥
        new Thread(test1::m1).start();
//        new Thread(test1::m2).start();

        //m11和m22互斥
        new Thread(test1::m11).start();
        //new Thread(test1::m22).start();

//        new Thread(Test1::m3).start();

        Object o = new Object();
        //m4和m5互斥
        /*new Thread(() -> {
            test1.m4(o);
        }).start();
        new Thread(() -> {
            test1.m5(o);
        }).start();*/
    }

    public void m1() {
        synchronized (this) {
            System.out.println("m1 " + Thread.currentThread().getName() + " running");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void m2() {
        synchronized (this) {
            System.out.println("m2 " + Thread.currentThread().getName() + " running");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void m11() {
        System.out.println("m1 " + Thread.currentThread().getName() + " running");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void m22() {
        System.out.println("m2 " + Thread.currentThread().getName() + " running");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void m3() {
        synchronized (Test1.class) {
            System.out.println("m2 " + Thread.currentThread().getName() + " running");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void m4(Object o) {
        synchronized (o) {
            System.out.println("m1 " + Thread.currentThread().getName() + " running");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void m5(Object o) {
        synchronized (o) {
            System.out.println("m1 " + Thread.currentThread().getName() + " running");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
